//
//  UITableView+RegisterCell.m
//  ChartsDemo
//
//  Created by Kary on 2022/10/2.
//

#import "UITableView+RegisterCell.h"

@implementation UITableView (RegisterCell)

- (void)registerCell:(id)cell {
    NSString *cellName = [self getCellName:cell];
    NSString *reuseIdentifier = [cellName stringByAppendingString:@"ID"];//标识符配套使用
    if ([self NibPath:cellName]) {
        [self registerNib:[UINib nibWithNibName:cellName bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    } else {
        [self registerClass:NSClassFromString(cellName) forCellReuseIdentifier:reuseIdentifier];
    }
}

- (id)dequeueReusableCell:(id)cell {
    NSString *cellName = [self getCellName:cell];
    NSString *reuseIdentifier = [cellName stringByAppendingString:@"ID"];
    UITableViewCell *newCell = [self dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (newCell == nil) {
        [self registerCell:cell];
    }
    return [self dequeueReusableCellWithIdentifier:reuseIdentifier];
}


- (id)dequeueReusableCell:(id)cell and:(NSIndexPath *)indexPath {
    NSString *cellName = [self getCellName:cell];
    NSString *reuseIdentifier = [cellName stringByAppendingString:@"ID"];
    UITableViewCell *newCell = [self dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (newCell == nil) {
        [self registerCell:cell];
    }
    return [self dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
}

- (NSString *)getCellName:(id)cell {
   NSString *cellName;
   if ([cell isKindOfClass:[NSString class]]) {
       cellName = cell;
   } else {
       cellName = NSStringFromClass(cell);
   }
   return  cellName;
}

// 通过判断nib是否存在来确认注册方式
- (BOOL)NibPath:(NSString *)name {
   NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"nib"];
   if (path == nil) { // 路径不存在
       return NO;
   } else { // 路径存在
       return YES;
   }
}


@end
